<?php
/**
* fashionelement.php
*
* Create on 2015-7-28
* Create by TT
*/
namespace haibao\app\data;

use haibao\app\model\filter\FashionElement as FashionFilter;
use haibao\app\model\data\FashionElement as FashionData;
use \haibao\frame\data\query\Condition;

class FashionElement extends \haibao\app\data\BaseMysql{
	private static $cacheTagDictName = 'TAG_DICT';
	private static $cacheTagTreeName = 'TAG_TREE';
	
	private $_tagDictArr = array();
	private $_retArr = array();
	
	public function __construct(){
		parent::__construct('\haibao\app\model\data\FashionElement');
	}
	
	public function getTopTag(){
		$filter = new FashionFilter();
		$filter->select(array(
				FashionFilter::CONDITION_FIELD_NAME_ID,
				FashionFilter::CONDITION_FIELD_NAME_NAME_CN,
				FashionFilter::CONDITION_FIELD_NAME_NAME_EN,
		));
		$filter->where(FashionFilter::CONDITION_FIELD_NAME_PARENT_ID, Condition::CONDITION_EQUAL, FashionData::TOP_PARENT_ID);
		$filter->where(FashionFilter::CONDITION_FIELD_NAME_STATUS, Condition::CONDITION_EQUAL, FashionData::STATUS_ENABLE);
		$filter->where(FashionFilter::CONDITION_FIELD_NAME_ID, Condition::CONDITION_EQUAL, FashionFilter::CONDITION_FIELD_NAME_TOPID, $filter, $filter);
		return $this->getAll($filter);
	}
	
	/**
	 * 获取所有标签树或某顶级标签下的所有标签
	 */
	public function getTagTree($topId = null){
		$cache = new \haibao\app\cache\Fashion();
		$cacheTagTree = null;
		$cacheTagTree = $cache->getFashionElements($topId);
		$tagTree = $cacheTagTree ? $cacheTagTree : $this->setTagTree();
		$retTree = $tagTree[intval($topId)];
		return !empty($retTree) ? array($topId => $retTree) : null;
	}
	
	/**
	 * 生成标签树结构数组
	 * @param $return 是否需要返回值
	 */
	private function setTagTree($return = true){
		$cache = new \haibao\app\cache\Fashion();
		$tagTree = array();
		$allTagDict = $this->getAllTagDict();
		foreach($allTagDict as $key=>$tag){
			if(isset($allTagDict[$tag[FashionFilter::CONDITION_FIELD_NAME_PARENT_ID]])){
				$allTagDict[$tag[FashionFilter::CONDITION_FIELD_NAME_PARENT_ID]]['children'][$tag[FashionFilter::CONDITION_FIELD_NAME_ID]] = &$allTagDict[$tag[FashionFilter::CONDITION_FIELD_NAME_ID]];
			}else{
				$tagTree[$tag[FashionFilter::CONDITION_FIELD_NAME_ID]] = &$allTagDict[$tag[FashionFilter::CONDITION_FIELD_NAME_ID]];
			}
		}
		$tagTree && $cache->setFashionElements(self::$cacheTagTreeName, serialize($tagTree));
		if($return){
			return $tagTree;
		}
	}
	
	/**
	 * 获取所有标签信息
	 * @return array(TagId=>array(TagName,ParentId))
	 */
	public function getAllTagDict(){
		$cache = new \haibao\app\cache\Fashion();
		$cacheTagArr = $cache->getFashionElements(self::$cacheTagDictName);
		return $cacheTagArr ? unserialize(base64_decode($cacheTagArr)) : $this->setAllTagDict();
	}
	
	/**
	 * 获取数据表中的所有可用标签保存到xcache中
	 * @param $return 是否需要返回值
	 */
	private function setAllTagDict($return = true){
		$cache = new \haibao\app\cache\Fashion();
		$filter = new FashionFilter();
		$filter->where($filter::CONDITION_FIELD_NAME_STATUS,Condition::CONDITION_EQUAL,\haibao\app\model\data\FashionElement::STATUS_ENABLE);
		$result = $this->getAll($filter);
		foreach ($result as $list){
			$tagId = $list->Id;
			$arrDict[$tagId] = array(
					$filter::CONDITION_FIELD_NAME_ID => intval($tagId),
					$filter::CONDITION_FIELD_NAME_NAME_CN =>$list->NameCN,
					$filter::CONDITION_FIELD_NAME_NAME_EN => $list->NameEN,
					$filter::CONDITION_FIELD_NAME_PARENT_ID => $list->ParentId,
					$filter::CONDITION_FIELD_NAME_TOPID => $list->TopId,
					$filter::CONDITION_FIELD_NAME_STATUS=>$list->Status
			);
		}
		$cache->setFashionElements(self::$cacheTagDictName, base64_encode(serialize($arrDict)));
		if($return){
			return $arrDict;
		}
	}
	
	/**
	 * 根据标签id查询标签信息
	 * @param int $tagId
	 * @param boolean $detail 只显示基本信息
	 */
	public function getTagById($tagId, $brief = true){
		$cache = new \haibao\app\cache\Fashion();
		$model = null;
		if ($brief){
			$cacheTagDict = unserialize(base64_decode($cache->getFashionElements(self::$cacheTagDictName)));
			if ($cacheTagDict){
				if(isset($cacheTagDict[$tagId])){
					$model = new \haibao\app\model\data\FashionElement();
					$model->loadArray($cacheTagDict[$tagId]);
				}
			}
		}
		if( empty($model) ){
			$model = $this->getOneById($tagId);
		}
		return $model;
	}
	
	public function getTagsByName($search,$isEnable)
	{
		if($isEnable){
			$tagStatus = "Status=%s";
			$tagStatusWhere = FashionData::STATUS_ENABLE;
		}else{
			$tagStatus = "Status<>%s";
			$tagStatusWhere = FashionData::STATUS_DISABLE;
		}
		$data = array();
		if (empty($search)) {
			$result = $this->query("select Id,NameCN,NameEN from `FashionElement` order by Id desc limit 10");
		} else {
			$sql = "select Id,NameCN,NameEN from `FashionElement` where (NameCN like %s or NameEN like %s or Id=%s) and ".$tagStatus." ORDER BY  REPLACE(NameCN,%s,'')  limit 30";
			$searchLike = '%' . $search . '%';
			$result = $this->query($sql, array(
					$searchLike, $searchLike, $search, $tagStatusWhere,$search
			));
		}
		while ($result->fetch_assoc()){
			$tagId = $result->getData('Id');
			$data[$tagId] = $result->getData('NameCN');
		}
		return $data;
	}
	
	/**
	 * @param string $tagName 标签名
	 * @param int $tagId 需要排除的标签id
	 */
	public function getTagByTagName($tagName, $tagId = null){
		$model = null;
		$sql = 'select * from FashionElement where (NameCN=%s or NameEN like %s) and Status<>%s';
		$aParam = array($tagName, '%,'.$tagName.',%', FashionData::STATUS_DISABLE);
		if($tagId){
			$sql .= ' and Id<>%s';
			array_push($aParam, $tagId);
		}
	
		$result = $this->query($sql, $aParam);
		while ($result->fetch_assoc()){
			$model = new FashionData();
			foreach($model->getKeyMap() as $keyName=>$keyType){
				$model->$keyName = $result->getData($keyType->getFieldName());
			}
		}
		return $model;
	}
	
	/**
	 * 根据标签id查找子级标签树（包含当前标签，当前标签为要查询的顶级标签）
	 * @param \haibao\cms\model\data\Tag $model
	 */
	public function getChildrenTreeByTagId($tagId){
		$tagInfo = $this->getTagById($tagId);
		$tagParentArr = $this->getParentsTagArr($tagId);
		$arrTree = $this->getTagTree($tagInfo->TopId);
		while (count($tagParentArr)){
			$model = array_pop($tagParentArr);
			if($model->ParentId == \haibao\app\model\data\FashionElement::TOP_PARENT_ID && isset($arrTree[$model->Id]['children'])){
				$arrTree = $arrTree[$model->Id]['children'];
			}else{
				$arrTree = isset($arrTree[$model->Id]['children']) ? $arrTree[$model->Id]['children'] : array($model->Id => $arrTree[$model->Id]);
			}
		}
		if(is_array($arrTree) && $tagInfo->Id == key($arrTree)){
			return $arrTree;
		} else {
			$retTag = $tagInfo->toArray();
			$retTag['children'] = $arrTree;
			return array($tagInfo->Id => $retTag);
		}
	}
	
	
	public function getParentsTagArr($tagId){
		$tagInfo = $this->getTagById($tagId);
		if($tagInfo){
			$this->_tagDictArr[$tagId] = $tagInfo;
			if($tagInfo->ParentId != \haibao\app\model\data\FashionElement::TOP_PARENT_ID){
				$this->getParentsTagArr($tagInfo->ParentId);
			}
		}
		return $this->_tagDictArr;
	}
	
	/**
	 * 获取父级频道标签树
	 */
	public function getParentsChannelTree($parentsTagArr){
		$parentsTagTree = array();
		if($parentsTagArr){
			foreach($parentsTagArr as $key=>$tag){
				if(isset($parentsTagArr[$tag[FashionFilter::CONDITION_FIELD_NAME_PARENT_ID]])){
					$parentsTagArr[$tag[FashionFilter::CONDITION_FIELD_NAME_PARENT_ID]]['children'][$tag[FashionFilter::CONDITION_FIELD_NAME_ID]] = &$parentsTagArr[$tag[FashionFilter::CONDITION_FIELD_NAME_ID]];
				}else{
					$parentsTagTree[$tag[FashionFilter::CONDITION_FIELD_NAME_ID]] = &$parentsTagArr[$tag[FashionFilter::CONDITION_FIELD_NAME_ID]];
				}
			}
		}
		return 	$parentsTagTree;
	}
	
	public function deleteTagById($tagId){
		$tagIdArr = $this->getChildrenTreeByTagId($tagId);
		$tagIds = (array)$this->multiarray_keys($tagIdArr, FashionFilter::CONDITION_FIELD_NAME_ID);
		$tagIdStr = implode(',', $tagIds);
			
		$str = preg_replace('/(\d+)/', '%s', $tagIdStr);
		$sql = 'update FashionElement set Status=%s where Id in ('.$str.')';
			
		$aParam = $tagIds;
		array_unshift($aParam, FashionData::STATUS_DISABLE);
		$this->query($sql, $aParam);
			
		$this->clearCache();
	}
	
	/**
	 * 返回多维数组的指定值
	 * @param array $arr 要查找的数组
	 * @param string $strict 只返回该值的数组。
	 */
	private function multiarray_keys($arr, $strict){
		foreach ($arr as $key=>$val){
			array_push($this->_retArr, $val[$strict]);
			if(isset($val['children'])){
				$this->multiarray_keys($val['children'], $strict);
			}
		}
		return $this->_retArr;
	}
	
	/**
	 * 是否存在子分类
	 * @param int $tagId
	 */
	public function isExitstChildTag($tagId){
		$sql = "select * from `FashionElement` where ParentId=%s and Status=%s";
		$result = $this->query($sql, array(intval($tagId),\haibao\app\model\data\FashionElement::STATUS_ENABLE));
		$data = array();
		while ($row = $result->fetch_assoc()){
			$model = new \haibao\app\model\data\FashionElement();
			$model->loadArray($row);
			array_push($data, $model);
		}
		return count($data);
	}
	
	public function clearCache(){
		$cache = new \haibao\app\cache\Fashion();
		$cache->unsetCache(self::$cacheTagDictName);
		$cache->unsetCache(self::$cacheTagTreeName);
	}
	public function addTag($model){
			$this->add($model);
			$this->clearCache();
	}
	public function updateTagById($model){
		$this->updateById($model->Id, array(
				FashionFilter::CONDITION_FIELD_NAME_NAME_CN => $model->NameCN,
				FashionFilter::CONDITION_FIELD_NAME_NAME_EN => $model->NameEN,
				FashionFilter::CONDITION_FIELD_NAME_PARENT_ID => $model->ParentId,
				FashionFilter::CONDITION_FIELD_NAME_TOPID => $model->TopId,
		));
	
		$this->clearCache();
	}
}